﻿using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using LinFu.IoC.Configuration;
using LinFu.IoC.Interfaces;
using System.Linq;

namespace CoreEx.Wcf.Server.Implementation
{
    [Implements(typeof(IInstanceProvider))]
    public class ServiceContainerInstanceProvider : IInstanceProvider, IInitialize
    {
        private readonly Type _serviceType;
        private IServiceContainer _serviceContainer;

        public ServiceContainerInstanceProvider(Type serviceType)
        {
            _serviceType = serviceType;
        }

        public object GetInstance(InstanceContext instanceContext)
        {
            return GetInstance(instanceContext, null);
        }

        public object GetInstance(InstanceContext instanceContext, Message message)
        {
            var type = _serviceType.GetInterfaces().First();

            return _serviceContainer.GetService(type);
        }

        public void ReleaseInstance(InstanceContext instanceContext, object instance)
        {

        }

        public void Initialize(IServiceContainer source)
        {
            _serviceContainer = source;
        }
    }
}